/*
 * Copyright (c) 2018-2999 北京国电高科科技有限公司 All rights reserved.
 *
 * https://www.tqmall.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.gdgk.shop.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gdgk.shop.bean.model.ScoreImportDetail;
import com.gdgk.shop.bean.model.User;
import com.gdgk.shop.common.util.PageParam;
import com.gdgk.shop.service.ScoreService;
import com.gdgk.shop.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.gdgk.shop.common.response.ServerResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * @author lgh on 2018/10/16.
 */
@Slf4j
@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ScoreService scoreService;


    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('admin:user:page')")
    public ServerResponseEntity<IPage<User>> page(User user, PageParam<User> page) {
        IPage<User> userPage = userService.page(page, new LambdaQueryWrapper<User>()
                .like(StrUtil.isNotBlank(user.getNickName()), User::getNickName, user.getNickName())
                .eq(user.getScore() != null, User::getScore, user.getScore())
                .eq(user.getStatus() != null, User::getStatus, user.getStatus())
                .eq(user.getBindStatus() != null, User::getBindStatus, user.getBindStatus()));
        for (User userResult : userPage.getRecords()) {
            userResult.setNickName(userResult.getNickName() == null ? "" : userResult.getNickName());
        }
        return ServerResponseEntity.success(userPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{userId}")
    @PreAuthorize("@pms.hasPermission('admin:user:info')")
    public ServerResponseEntity<User> info(@PathVariable("userId") String userId) {
        User user = userService.getById(userId);
        user.setNickName(user.getNickName() == null ? "" : user.getNickName());
        return ServerResponseEntity.success(user);
    }

    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin:user:update')")
    public ServerResponseEntity<Void> update(@RequestBody User user) {
        user.setModifyTime(new Date());
        user.setNickName(user.getNickName() == null ? "" : user.getNickName());
        userService.updateById(user);
        return ServerResponseEntity.success();
    }

    /**
     * 删除
     */
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('admin:user:delete')")
    public ServerResponseEntity<Void> delete(@RequestBody String[] userIds) {
        userService.removeByIds(Arrays.asList(userIds));
        return ServerResponseEntity.success();
    }


    /**
     * 导入积分记录  By -lyk
     */
    @PostMapping("/importExcel")
//    @PreAuthorize("@pms.hasPermission('admin:user:info')")
    public ServerResponseEntity<List<ScoreImportDetail>> importExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ServerResponseEntity.showFailMsg("请选择一个文件上传");
        }
        log.info("已接收文件");
        System.out.println("已接收文件");

        // 1. 导入记录入库（根据表字段添加记录）
        //  (1) 写入记录表
        try {
            Long recordId = scoreService.resolveExcel(file);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  (2) 写入批次明细表

        // 2. 遍历记录，查找user表：
        //    如果该手机号已在库中，根据该手机号做修改（调用函数一和二是原子操作）
        //     (1) 添加 最新积分（函数一：修改user表，接收参数:手机号  该函数还提供给 绑定手机号增加积分操作）
        //     (2) 修改记录表中状态（函数二：修改记录表状态表示已修改）

        //    如果不在库中，不执行操作


//        try {
//            excelService.importExcel(file);
//            return ServerResponseEntity.success(User);
//        } catch (Exception e) {
//            // 处理异常
//            return ServerResponseEntity.showFailMsg("解析文件时出错: " + e.getMessage());
//        }
//        User user = userService.getById(userId);
//        user.setNickName(user.getNickName() == null ? "" : user.getNickName());
        return ServerResponseEntity.success(null);
    }


    @PostMapping("/queryScore")
    public ServerResponseEntity<User> queryScoreByMobileNumber(@RequestParam("mobileNumber") String mobileNumber) {
        if (StringUtils.isBlank(mobileNumber) && mobileNumber.length() != 11) {
            // 返回手机号格式错误
            log.info("查询的用户手机号码格式异常! ");
            return ServerResponseEntity.showFailMsg("查询的用户手机号码格式异常! ");
        }
        try {
            User user = new User();
            user.setScore(scoreService.queryScoreByMobileNumber(mobileNumber));
            return ServerResponseEntity.success(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
